import $ from "jquery";
import { useDebounceFn } from "@vueuse/core";

// console.log("window.PDFViewerApplication: ", window.PDFViewerApplication);
// let sidebarActive = window.PDFViewerApplication?.pdfSidebar.active;
// let sidebarIsOpen = window.PDFViewerApplication?.pdfSidebar.isOpen;

const _setActiveTab = useDebounceFn(() => {
  console.log("1111111111111111111111111111111111111111111111", window.PDFViewerApplication.pdfSidebar);
  let sidebarActive = window.PDFViewerApplication.pdfSidebar.active;
  let sidebarIsOpen = window.PDFViewerApplication.pdfSidebar.isOpen;
  if (sidebarIsOpen) {
    let $btn = $(`#sidebarButtons .item-btn:eq(${sidebarActive - 1})`);
    $btn.addClass("active");
    if(sidebarActive === 3) {
      provideHome.isLoadingSignHistory = true;
    }else {
      provideHome.isLoadingSignHistory = false;
    }
  }
});

const setActiveTab = () => {
  _setActiveTab();
};

const removeActiveTab = () => {
  $("#sidebarButtons .active").removeClass("active");
};

// 监听左侧侧边栏的显示与隐藏
const watchSideBarIsOpen = () => {
  let sidebarIsOpen = window.PDFViewerApplication.pdfSidebar.isOpen;
  Object.defineProperty(window.PDFViewerApplication.pdfSidebar, "isOpen", {
    get() {
      return sidebarIsOpen;
    },
    set(newValue) {
      sidebarIsOpen = newValue;
      if (sidebarIsOpen) {
        setActiveTab();
      } else {
        removeActiveTab();
      }
    },
  });
};

// 监听 页面、签章历史、书签的tab切换
const watchSideBarActive = () => {
  let sidebarActive = window.PDFViewerApplication.pdfSidebar.active;
  let sidebarIsOpen = window.PDFViewerApplication.pdfSidebar.isOpen;
  Object.defineProperty(window.PDFViewerApplication.pdfSidebar, "active", {
    get() {
      return sidebarActive;
    },
    set(newValue) {
      if (sidebarIsOpen) {
        // 处于显示状态
        if (newValue == sidebarActive) {
          // 点击已选中按钮，收起sidebar面板
          window.PDFViewerApplication.pdfSidebar.close();
        }
      } else {
        window.PDFViewerApplication.pdfSidebar.open();
      }
      sidebarActive = newValue;
      removeActiveTab();
      setActiveTab();
    },
  });
};

// 监听搜索框
let findbarIsOpen;
const watchFindbarIsOpen = () => {
  Object.defineProperty(window.PDFViewerApplication.findBar, "opened", {
    get() {
      return findbarIsOpen;
    },
    set(newValue) {
      findbarIsOpen = newValue;
      if (findbarIsOpen) {
        $("#viewFind").addClass("active");
      } else {
        $("#viewFind").removeClass("active");
      }
    },
  });
};

// 监听并触发
function watchToolbarChange() {
  if (window.PDFViewerApplication.pdfSidebar) {
    watchSideBarIsOpen();
    watchSideBarActive();
    watchFindbarIsOpen();
  } else {
    setTimeout(() => {
      watchToolbarChange();
    }, 1000);
  }
}

export const helperToolbar = {
  watchToolbarChange,
};
